@file:kotlin.jvm.JvmName("PluginModuleFactoryImpl")

package com.ysten.tv.plugin.impl


import android.content.Context
import android.os.Bundle
import com.baymx.plugin.demo.ViewComponent
import com.billy.cc.core.component.CC
import com.ysten.tv.plugin.protocol.LifecyclePluginModule
import com.ysten.tv.plugin.protocol.PluginModuleFactory
import java.io.File

class PluginModuleFactoryImpl : PluginModuleFactory {

    companion object{
        lateinit var PContent: Context
    }
    override fun getPluginModule(pluginContext: Context): LifecyclePluginModule {
        PContent = pluginContext
        val viewComponent = ViewComponent()
        return object : LifecyclePluginModule {
            override fun onCreate(saveInstanceState: Bundle?) {
                CC.registerComponent(viewComponent)
            }

            override fun onSaveInstanceState(bundle: Bundle) {

            }

            override fun onDestroy() {
                CC.unregisterComponent(viewComponent)
            }

            override fun inject(hostContext: Context) {
                initAssets(pluginContext ,hostContext)
            }
        }
    }

    private fun initAssets(pluginContext: Context, hostContext: Context) {
        kotlin.runCatching {
            println("initAssets")
            val assets = pluginContext.resources.assets
            val m = assets.javaClass.getDeclaredMethod("addAssetPath" ,String::class.java)
            println("initAssets $m")
            m.isAccessible = true
            m.invoke(assets ,File(hostContext.filesDir ,"shadow/plugin/demo/1/tmp.apk").absolutePath)
        }.onFailure {
            println("initAssets error $it")
        }
    }
}